//
//  lostViewController.m
//  Find
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "LostViewController.h"
#import "LostPhotoCollectionViewCell.h"
#import "LostListTableViewCell.h"
#import "MapViewController.h"
#import "LostDetailViewController.h"
#import "CollectionViewModel.h"
#import <CoreLocation/CoreLocation.h>


#define KLineSpacing 20


@interface LostViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain)NSMutableArray *dataArray;
@property (nonatomic, retain)UISegmentedControl *segmented;
// collectionView的data
@property (nonatomic, retain)NSMutableArray *imageDataArray;

// 判断是否触发跳转 解决 CollectionView 重复跳转
@property (nonatomic, assign) BOOL isPush;


@end

@implementation LostViewController
- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:87/255.0 green:191/255.0 blue:255/255.0 alpha:1];
    // 调用 添加界面内容
    [self addSubViews];
}

#pragma  mark --- 获取丢失数据
- (void)setUpTableViewData
{
    AVQuery *query = [LostMessageModel query];
//    query.cachePolicy = kAVCachePolicyCacheElseNetwork;
//    query.maxCacheAge = 60 * 60;
    // 按发帖时间降序排列
    [query orderByDescending:@"createdAt"];
    // 限制查询返回数
    [query setLimit:self.limit];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.dataArray = [NSMutableArray arrayWithArray:objects];
        self.imageDataArray = [NSMutableArray array];

        for (LostMessageModel *model in objects) {
            NSString *urlString = [model.imageArray firstObject];
            if (urlString) {
                CollectionViewModel *imageModel = [[CollectionViewModel alloc] init];
                imageModel.picUrl = urlString;
                imageModel.objectID = model.objectId;
                imageModel.title = model.title;
                [self.imageDataArray addObject:imageModel];
            }
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.lostTableView reloadData];
            [self.lostCollectionView reloadData];
            [self.lostTableView.header endRefreshing];
            [self.lostTableView.footer endRefreshing];
        });
    }];
}


#pragma mark  -- 添加页面内容
- (void)addSubViews
{
    // 左上角图标
    UIBarButtonItem * lostLeftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting"] style:(UIBarButtonItemStyleDone) target:self action:@selector(lostLeftBarButtonAction:)];
    self.navigationItem.leftBarButtonItem = lostLeftBarButton;
     lostLeftBarButton.tintColor= [UIColor whiteColor];
    // 右上角图标
    UIBarButtonItem * lostRightBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:(UIBarButtonItemStylePlain) target:self action:@selector(lostRightBarButtonAction:)];
    lostRightBarButton.tintColor= [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = lostRightBarButton;
    
    // 设置navigationBar 背景颜色 用图片
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iconfont-navbar-back"] forBarMetrics:UIBarMetricsDefault];
    
    
#pragma mark --- collectionViewFlowLayout
    
    // 自定义 collectionViewFlowLayout
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = kFindPhotoSpacing;
    flowLayout.minimumInteritemSpacing = kFindPhotoSpacing;
    flowLayout.itemSize = CGSizeMake(kFindPhotoMainImageViewWidth, kFindPhotoMainImageViewHeight+kFindPhotoAddressImageViewHight);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(kFindPhotoSectionInset, kFindPhotoSectionInset, kFindPhotoSectionInset, kFindPhotoSectionInset);
    
    // 初始化集合视图
    self.lostCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 113) collectionViewLayout:flowLayout];
    // 设置代理
    self.lostCollectionView.delegate = self;
    self.lostCollectionView.dataSource = self;
    self.lostCollectionView.backgroundColor = [UIColor whiteColor];
    
#warning ===
    self.lostCollectionView.header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.lostCollectionView.header beginRefreshing];
    
    MJChiBaoZiFooter *collectionfooter = [MJChiBaoZiFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    collectionfooter.automaticallyRefresh = NO;
    self.lostCollectionView.footer = collectionfooter;
#warning ===
    
    
    // 添加视图
    [self.view addSubview:self.lostCollectionView];
    
    // 注册cell
    [self.lostCollectionView registerClass:[FindPhotoCollectionCell class] forCellWithReuseIdentifier:@"FindPhotoCollectionCell"];
    
#pragma  mark -- tableview 
    self.lostTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 113) style:(UITableViewStylePlain)];
    self.navigationController.navigationBar.translucent = NO;
    self.lostTableView.delegate = self;
    self.lostTableView.dataSource = self;
    [self.view addSubview:self.lostTableView];
    
    self.lostTableView.header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.lostTableView.header beginRefreshing];
    
    MJChiBaoZiFooter *footer = [MJChiBaoZiFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyRefresh = NO;
    self.lostTableView.footer = footer;

    [self addLeft];
    [self addTitleSegment];
    
    // 设置 初值跳转为 NO
    self.isPush = NO;
    
}

- (void)loadNewData{
    self.limit = 10;
    [self setUpTableViewData];
    [self setUpCollectionViewData];
}
- (void)loadMoreData{
    self.limit = self.limit + 10;
    [self setUpTableViewData];
    [self setUpCollectionViewData];
}

# pragma mark -- 左边按钮布局视图
- (void)addLeft{
    
    self.visualView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    self.visualView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.visualView.alpha = 0;
    [self.view addSubview:self.visualView];
    
    // 排序的button
    self.sortBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-80, -90, 80, 90)];
    self.sortBgImageView.image = [UIImage imageNamed:@"bubble"];
    [self.view addSubview:self.sortBgImageView];
    self.sortBgImageView.userInteractionEnabled = YES;
    self.sortAddressButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sortAddressButton.frame = CGRectMake(0, 23, CGRectGetWidth(self.sortBgImageView.frame), 30);
    self.sortAddressButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.sortAddressButton setTitle:@"地址排序" forState:UIControlStateNormal];
    [self.sortAddressButton addTarget:self action:@selector(actionSortAddressButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.sortBgImageView addSubview:self.sortAddressButton];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.sortAddressButton.frame), CGRectGetMaxY(self.sortAddressButton.frame), CGRectGetWidth(self.sortAddressButton.frame), 3)];
    lineLabel.backgroundColor = [UIColor whiteColor];
    [self.sortBgImageView addSubview:lineLabel];
    
    self.sortTimeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sortTimeButton.frame = CGRectMake(CGRectGetMinX(lineLabel.frame), CGRectGetMaxY(lineLabel.frame), CGRectGetWidth(self.sortAddressButton.frame), 30);
    [self.sortTimeButton setTitle:@"时间排序" forState:UIControlStateNormal];
    [self.sortTimeButton addTarget:self action:@selector(actionSortTimeButton:) forControlEvents:UIControlEventTouchUpInside];
    self.sortTimeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.sortBgImageView addSubview:self.sortTimeButton];
}


#pragma mark -- 按地址排序
- (void)actionSortAddressButton:(UIButton *)sender{
    [UIView animateWithDuration:0.3 animations:^{
        self.sortBgImageView.frame = CGRectMake(-80, -90, 80, 90);
        self.visualView.alpha = 0;
    }];
    [self setUpCollectionViewData];

}
- (void)setUpCollectionViewData
{
    AVQuery *query = [LostMessageModel query];
//    query.cachePolicy = kAVCachePolicyCacheElseNetwork;
//    query.maxCacheAge = 60 * 60;
    [query setLimit:self.limit];
    [query orderByAscending:@"distance"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        self.dataArray = [NSMutableArray arrayWithArray:objects];
        self.imageDataArray = [NSMutableArray array];
        for (LostMessageModel *model in objects) {
            NSString *urlString = [model.imageArray firstObject];
            if (urlString) {
                CollectionViewModel *imageModel = [[CollectionViewModel alloc] init];
                imageModel.picUrl = urlString;
                imageModel.objectID = model.objectId;
                imageModel.title = model.title;
                [self.imageDataArray addObject:imageModel];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //[self.lostTableView reloadData];
            [self.lostCollectionView reloadData];
            [self.lostCollectionView.header endRefreshing];
            [self.lostCollectionView.footer endRefreshing];
           // [self.lostCollectionView reloadData];
        });
    }];
}
#pragma mark -- 按时间排序
- (void)actionSortTimeButton:(UIButton *)sender{
    [UIView animateWithDuration:0.3 animations:^{
        self.sortBgImageView.frame = CGRectMake(-80, -90, 80, 90);
        self.visualView.alpha = 0;
    }];
    [self setUpTableViewData];
}

// 标题创建UISegmentedControl
- (void)addTitleSegment
{
    // 创建view 作为navigation  的 titleView
    UIView * lostTitleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kFindNavBarTitleViewWidth, kFindNavBarTitleViewHeight)];
//    lostTitleView.backgroundColor = [UIColor yellowColor];
    self.navigationItem.titleView = lostTitleView;
    
    // 添加segment
    NSArray *segmentItems = @[@"寻", @"觅"];
    self.segmented = [[UISegmentedControl alloc] initWithItems:segmentItems];
    self.segmented.frame = CGRectMake(0, 0, kFindNavBarTitleViewWidth, kFindNavBarTitleViewHeight);
    self.segmented.backgroundColor = [UIColor colorWithRed:0.035 green:0.580 blue:0.827 alpha:1];
    self.segmented.layer.cornerRadius = kFindNavBarTitleViewHeight/2;
    self.segmented.layer.masksToBounds = YES;
    self.segmented.layer.borderWidth = 1; // 边框宽度
    self.segmented.layer.borderColor = kFindListCellLabelTextColor.CGColor; // 边框颜色
    self.segmented.tintColor = [UIColor whiteColor];
    self.segmented.selectedSegmentIndex = 0;
    
    [self.segmented addTarget:self action:@selector(actionSegmented:) forControlEvents:UIControlEventValueChanged];
    
    [lostTitleView addSubview:self.segmented];

}

#pragma mark -- segment
- (void)actionSegmented:(UISegmentedControl *)sender{
    switch (sender.selectedSegmentIndex) {
        case 0:
            [self.view sendSubviewToBack:self.lostCollectionView];

            break;
        case 1:
            [self.view sendSubviewToBack:self.lostTableView];

            break;
        default:
            break;
    }
}

#pragma mark -- 左上角点击事件
- (void)lostLeftBarButtonAction:(UINavigationItem *)lostLeftButton
{
    if (self.sortBgImageView.frame.origin.x == -80) {
        [UIView animateWithDuration:0.3 animations:^{
            self.sortBgImageView.frame = CGRectMake(0, 0, 80, 90);
            self.visualView.alpha = 0.8;
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            self.sortBgImageView.frame = CGRectMake(-80, -90, 80, 90);
            self.visualView.alpha = 0;
        }];
    }

}

#pragma mark -- 右上角点击事件
- (void)lostRightBarButtonAction:(UINavigationItem *)lostRightButton
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark -- 实现tableview代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString * identifier = @"lostViewController";
    LostListTableViewCell * listcell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (listcell == nil) {
        listcell = [[LostListTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    listcell.backgroundColor = [UIColor whiteColor];
    LostMessageModel *lostModel = self.dataArray[indexPath.row];

    AVUser *user1 = lostModel.user;
//    AVUser *user2 = [AVQuery getUserObjectWithId:user1.objectId];  // 同步请求数据导致界面卡顿
    AVQuery * query = [AVQuery queryWithClassName:@"_User"];
    [query  getObjectInBackgroundWithId:user1.objectId block:^(AVObject *object, NSError *error) {
        listcell.listTitleLabel.text =  [object objectForKey:@"username"];
        NSString *urlString = [[object valueForKey:@"photoImage"] getThumbnailURLWithScaleToFit:NO width:100 height:100];
        [listcell.listImage sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    }];

    // 距离
    AVUser *user = [AVUser currentUser];
    
    CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:[[user valueForKey:@"latitude"] floatValue] longitude:[[user valueForKey:@"longitude"] floatValue]];
    CLLocation *publishLocation = [[CLLocation alloc] initWithLatitude:[lostModel.latitude floatValue] longitude:[lostModel.longitude floatValue]];
    
    if ([lostModel.latitude floatValue]  == 0 && [lostModel.longitude floatValue] == 0) {
       listcell.listDistance.text = @"未定位";
    } else {
        CLLocationDistance distance = [userLocation distanceFromLocation:publishLocation];
        lostModel.distance =[NSNumber numberWithFloat:distance];
        [lostModel saveInBackground];
      if (distance < 1000){
       listcell.listDistance.text = [NSString stringWithFormat:@"%dm",(int)distance];
      } else {
       listcell.listDistance.text = [NSString stringWithFormat:@"%.1fkm",(distance / 1000)];
    }
    }

    // 用户名
    listcell.listTextLabel.text = lostModel.context;
    listcell.listTextLabel.alpha = 0.8;
    // 上传的日期
     NSDateFormatter *dateFoematter = [[NSDateFormatter alloc] init];
    [dateFoematter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSRange range = NSMakeRange(5, 11);
    listcell.listTimeLabel.text = [[dateFoematter stringFromDate: lostModel.createdAt] substringWithRange:range];
    // 位置
    listcell.listAddressLabel.text = lostModel.location;

    
    UIView *selectView = [[UIView alloc] init];
    selectView.backgroundColor = [UIColor clearColor];
    listcell.selectedBackgroundView = selectView;
    
    
    return listcell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *objectID = [self.dataArray[indexPath.row] objectId];
    
    LostDetailViewController *detailVC = [[LostDetailViewController alloc] init];
//    // 设置详情界面返回按钮
//    UIBarButtonItem * lostBackButton = [[UIBarButtonItem alloc] init];
//    lostBackButton.title = @" ";
//    lostBackButton.tintColor = [UIColor whiteColor];
////    self.navigationItem.backBarButtonItem
//    self.navigationItem.backBarButtonItem = lostBackButton;
    //
    detailVC.objectID = objectID;
  //  detailVC.publishInfoType = @"lost";
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark -- 实现collectionView 方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

   return self.imageDataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FindPhotoCollectionCell * lostCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FindPhotoCollectionCell" forIndexPath:indexPath];
    CollectionViewModel *model = self.imageDataArray[indexPath.row];
  
     NSURL *url = [NSURL URLWithString:model.picUrl];
       [lostCell.mainImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder2"]];
        lostCell.addressLabel.text = model.title;

    return lostCell;
  
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isPush == NO) {
    CollectionViewModel *model = self.imageDataArray[indexPath.row];
    LostDetailViewController *lostVC = [[LostDetailViewController alloc] init];
//    // 设置详情界面返回按钮
//    UIBarButtonItem * lostBackButton = [[UIBarButtonItem alloc] init];
//    lostBackButton.title = @" ";
//    lostBackButton.tintColor = [UIColor whiteColor];
//    self.navigationItem.backBarButtonItem = lostBackButton;
   
    
    // 关闭点击方法
//    [collectionView setUserInteractionEnabled:NO];
    
         lostVC.objectID = model.objectID;
        [self.navigationController pushViewController:lostVC animated:YES];
    }
    self.isPush = YES;
   
}

#pragma mark --- 将要出现的时候打开 collectionView 交互功能
- (void)viewDidAppear:(BOOL)animated
{
    // 将跳转值重置为 NO
    self.isPush = NO;
//    [self.lostCollectionView setUserInteractionEnabled:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
